<?php
/*
	[UCenter Home] (C) 2007-2008 Comsenz Inc.
	$Id: cp_comment.php 10586 2008-12-10 06:53:47Z liguode $
*/

if(!defined('IN_UCHOME')) {
	exit('Access Denied');
}

include_once(S_ROOT.'./source/function_bbcode.php');
include_once(S_ROOT.'./source/function_cp.php');

//共用变量
$tospace = $pic = $blog = $album = $share = array();


if(submitcheck('commentsubmit')) {

	if(!checkperm('allowcomment')) {
       	$r['err'] = '对不起，您暂时不能写评论';
        echo json_encode($r);
        exit;
	}

	//实名认证
	ckrealname('comment');
	
	//新用户见习
	cknewuser();

	//判断是否发布太快
	$waittime = interval_check('post');
	if($waittime > 0) {
		//showmessage('operating_too_fast','',1,array($waittime));
	}
   
	$message = getstr($_POST['message'], 0, 1, 1, 1, 2); 

	if(strlen($message) < 2) {
        $r['err'] = "能否再多写几个词(不少于一个中文字)";
        echo json_encode($r);
        exit;
	}

	//摘要
	$summay = getstr($message, 150, 1, 1, 0, 0, -1);

	$id = intval($_POST['id']);

	//引用评论
	$cid = empty($_POST['cid'])?0:intval($_POST['cid']);
	$comment = array();
	if($cid) {
		$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('comment')." WHERE cid='$cid' AND id='$id' AND idtype='$_POST[idtype]'");
		$comment = $_SGLOBAL['db']->fetch_array($query);
		if($comment && $comment['authorid'] != $_SGLOBAL['supe_uid']) {
			//实名
			realname_set($comment['authorid'], $comment['author']);
			realname_get();
			
			$comment['message'] = preg_replace("/\<div class=\"quote\"\>\<span class=\"q\"\>.*?\<\/span\>\<\/div\>/is", '', $comment['message']);
			//bbcode转换
			$comment['message'] = html2bbcode($comment['message']);
			$message = addslashes("<div class=\"quote\"><span class=\"q\"><b>".$_SN[$comment['authorid']]."</b>: ".getstr($comment['message'], 150, 0, 0, 0, 2, 1).'</span></div>').$message;
			if($comment['idtype']=='uid') {
				$id = $comment['authorid'];
			}
		} else {
			$comment = array();
		}
	}

	//对输入的id、idtype进行检查
	checkcomment($id, $_POST['idtype']);

	//事件
	$fs = array();
	$fs['icon'] = 'comment';
	$fs['target_ids'] = $fs['friend'] = '';

	switch ($_POST['idtype']) {
		case 'uid':
			//事件
			$fs['icon'] = 'wall';
			$fs['title_template'] = cplang('feed_comment_space');
			$fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>");
			$fs['body_template'] = '';
			$fs['body_data'] = array();
			$fs['body_general'] = '';
			$fs['images'] = array();
			$fs['image_links'] = array();
			break;
		case 'picid':
			//事件
			$fs['title_template'] = cplang('feed_comment_image');
			$fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>");
			$fs['body_template'] = '{pic_title}';
			$fs['body_data'] = array('pic_title'=>$pic['title']);
			$fs['body_general'] = $summay;
			$fs['images'] = array(mkpicurl($pic));
			$fs['image_links'] = array("space.php?uid=$tospace[uid]&do=album&picid=$pic[picid]");
			$fs['target_ids'] = $album['target_ids'];
			$fs['friend'] = $album['friend'];
			break;
		case 'spicid':
			//事件
			$fs['title_template'] = cplang('feed_comment_image');
			$fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>");
			$fs['body_template'] = '{pic_title}';
			$fs['body_data'] = array('pic_title'=>$pic['title']);
			$fs['body_general'] = $summay;
			$fs['images'] = array(mkpicurl($pic));
			$fs['image_links'] = array("site.php?ac=image&type=spot&id=".$_POST['ext_id']."&picid=".$pic[picid]);
			break;
		case 'ppicid':
			//事件
			$fs['title_template'] = cplang('feed_comment_image');
			$fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>");
			$fs['body_template'] = '{pic_title}';
			$fs['body_data'] = array('pic_title'=>$pic['title']);
			$fs['body_general'] = $summay;
			$fs['images'] = array(mkpicurl($pic));
			$fs['image_links'] = array("site.php?ac=image&type=profile&id=".$_POST['ext_id']."&picid=".$pic[picid]);
			break;
        case 'profid':
			//档案评论
			$fs['title_template'] = cplang('feed_comment_prof');
			$fs['title_data'] = array('touser'=>"<a href=\"site.php?ac=profile&op=index&profid=$id\">".$tospace['prof_name']."</a>");
			$fs['body_template'] = '';
			$fs['body_data'] = array();
			$fs['body_general'] = $summay;
			$fs['images'] = array();
			$fs['image_links'] = array();
			break;
		case 'blogid':
			//更新评论统计
			$_SGLOBAL['db']->query("UPDATE ".tname('blog')." SET replynum=replynum+1 WHERE blogid='$id'");
			//事件
			$fs['title_template'] = cplang('feed_comment_blog');
			$fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>", 'blog'=>"<a href=\"space.php?uid=$tospace[uid]&do=blog&id=$id\">$blog[subject]</a>");
			$fs['body_template'] = '';
			$fs['body_data'] = array();
			$fs['body_general'] = '';
			$fs['target_ids'] = $blog['target_ids'];
			$fs['friend'] = $blog['friend'];
			break;
		case 'sid':
			//事件
			$fs['title_template'] = cplang('feed_comment_share');
			$fs['title_data'] = array('touser'=>"<a href=\"space.php?uid=$tospace[uid]\">".$_SN[$tospace['uid']]."</a>", 'share'=>"<a href=\"space.php?uid=$tospace[uid]&do=share&id=$id\">".str_replace(cplang('share_action'), '', $share['title_template'])."</a>");
			$fs['body_template'] = '';
			$fs['body_data'] = array();
			$fs['body_general'] = '';
			break;
	}

	$setarr = array(
		'uid' => $tospace['uid'],
		'id' => $id,
		'idtype' => $_POST['idtype'],
		'authorid' => $_SGLOBAL['supe_uid'],
		'author' => $_SGLOBAL['supe_username'],
		'dateline' => $_SGLOBAL['timestamp'],
		'message' => $message,
		'ip' => getonlineip()
	);
	//入库
	$cid = inserttable('comment', $setarr, 1);

	switch ($_POST['idtype']) {
		case 'uid':
			$n_url = "space.php?uid=$tospace[uid]&do=wall&cid=$cid";
			$note_type = 'wall';
			$note = cplang('note_wall', array($n_url));
			$q_note = cplang('note_wall_reply', array($n_url));
			if($comment) {
				$msg = 'note_wall_reply_success';
				$magvalues = array($_SN[$tospace['uid']]);
			} else {
				$msg = 'do_success';
				$magvalues = array();
			}
			$msgtype = 'comment_friend';
			break;
		case 'picid':
			$n_url = "space.php?uid=$tospace[uid]&do=album&picid=$id&cid=$cid";
			$note_type = 'piccomment';
			$note = cplang('note_pic_comment', array($n_url));
			$q_note = cplang('note_pic_comment_reply', array($n_url));
			$msg = 'do_success';
			$magvalues = array();
			$msgtype = 'photo_comment';
			break;
		case 'spicid':
			$n_url = "site.php?ac=image&type=spot&id=".$_POST['ext_id']."&picid=".$pic[picid];
			$note_type = 'piccomment';
			$note = cplang('note_pic_comment', array($n_url));
			$q_note = cplang('note_pic_comment_reply', array($n_url));
			$msg = 'do_success';
			$magvalues = array();
			$msgtype = 'photo_comment';
			break;
		case 'ppicid':
			$n_url = "site.php?ac=image&type=profile&id=".$_POST['ext_id']."&picid=".$pic[picid];
			$note_type = 'piccomment';
			$note = cplang('note_pic_comment', array($n_url));
			$q_note = cplang('note_pic_comment_reply', array($n_url));
			$msg = 'do_success';
			$magvalues = array();
			$msgtype = 'photo_comment';
			break;
        case 'profid':
            $n_url = "site.php?ac=profile&op=index&profid=$id";
			$note_type = 'profcomment';
			$note = cplang('note_prof_comment', array($n_url));
			$q_note = cplang('note_prof_comment_reply', array($n_url));
			$msg = 'do_success';
			$magvalues = array();
			$msgtype = 'prof_comment';
			break;
		case 'blogid':
			//通知
			$n_url = "space.php?uid=$tospace[uid]&do=blog&id=$id&cid=$cid";
			$note_type = 'blogcomment';
			$note = cplang('note_blog_comment', array($n_url, $blog['subject']));
			$q_note = cplang('note_blog_comment_reply', array($n_url));
			$msg = 'do_success';
			$magvalues = array();
			$msgtype = 'blog_comment';
			break;
		case 'sid':
			//分享
			$n_url = "space.php?uid=$tospace[uid]&do=share&id=$id&cid=$cid";
			$note_type = 'sharecomment';
			$note = cplang('note_share_comment', array($n_url));
			$q_note = cplang('note_share_comment_reply', array($n_url));
			$msg = 'do_success';
			$magvalues = array();
			$msgtype = 'share_comment';
			break;
	}

    if ($comment['authorid']) {
	    //发送邮件通知
	    $touid = empty($comment['authorid']) ? $tospace['uid'] : $comment['authorid'];
	    smail($touid, '', cplang($msgtype, array($_SN[$space['uid']], shtmlspecialchars(getsiteurl().$n_url))));
    }

	if(empty($comment)) {
		//非引用评论
		//事件发布
		//if(ckprivacy('comment', 1)) 
        {
			feed_add($fs['icon'], $fs['title_template'], $fs['title_data'], $fs['body_template'], $fs['body_data'], $fs['body_general'],$fs['images'], $fs['image_links'], $fs['target_ids'], $fs['friend']);
		}
	} elseif($comment['authorid'] != $_SGLOBAL['supe_uid']) {
		//引用评论, 则通知对方
		notification_add($comment['authorid'], $note_type, $q_note);
	}

	//积分
	//updatespacestatus('get', 'prof_cmt');

	//if($_POST['idtype'] == 'profid') {
	//	updatespacestatus('get', 'prof_cmt');
	//} else {
    updatespacestatus('get', 'prof_cmt');
	//}
	
	$r['msg'] = '';
	echo json_encode($r);
	exit;

	showmessage($msg, $_POST['refer'], 0, $magvalues);
}

$cid = empty($_GET['cid'])?0:intval($_GET['cid']);

//编辑
if($_GET['op'] == 'edit') {

	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('comment')." WHERE cid='$cid' AND authorid='$_SGLOBAL[supe_uid]'");
	if(!$comment = $_SGLOBAL['db']->fetch_array($query)) {
        $r['err'] = "没有权限";
        echo json_encode($r);
        exit; 
	}

	//提交编辑
	//if(submitcheck('editsubmit')) {

	$message = getstr($_POST['message'], 0, 1, 1, 1, 2);
	if(strlen($message) < 2) {
        $r['err'] = "评论至少写一个汉字！";
        echo json_encode($r);
        exit; 
    }

	updatetable('comment', array('message'=>$message), array('cid'=>$comment['cid']));

	//showmessage('do_success', $_POST['refer'], 0);
	//}

	//bbcode转换
	$r['message'] = $message;//显示用
	//$r['message'] = html2bbcode($comment['message']);//显示用
    $r['cid'] = $cid;
    echo json_encode($r);
    exit; 

} elseif($_GET['op'] == 'delete') {

	if(submitcheck('deletesubmit')) {
		if(deletecomments(array($cid))) {
			showmessage('do_success', $_POST['refer'], 0);
		} else {
			showmessage('no_privilege');
		}
	}

} elseif($_GET['op'] == 'reply') {

	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('comment')." WHERE cid='$cid'");
	if(!$comment = $_SGLOBAL['db']->fetch_array($query)) {
		showmessage('comments_do_not_exist');
	}

} else {

	showmessage('no_privilege');
}

include template('site/tpl/cp_comment');

//检查
function checkcomment($id, $idtype) {
	global $_SGLOBAL;
	global $tospace, $pic, $blog, $album, $share;

	switch ($idtype) {
		case 'uid':
			//检索空间
			$tospace = getspace($id);
			break;
		case 'picid':
			//检索图片
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('pic')." WHERE picid='$id' LIMIT 1");
			$pic = $_SGLOBAL['db']->fetch_array($query);
			//图片不存在
			if(empty($pic)) {
				showmessage('view_images_do_not_exist');
			}

			//检索空间
			$tospace = getspace($pic['uid']);

			//获取相册
			$album = array();
			if($pic['albumid']) {
				$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('album')." WHERE albumid='$pic[albumid]'");
				if(!$album = $_SGLOBAL['db']->fetch_array($query)) {
					updatetable('pic', array('albumid'=>0), array('albumid'=>$pic['albumid']));//相册丢失
				} else {
					if($album['target_ids']) {
						$album['target_ids'] .= ",$album[uid]";
					}
				}
			}
			break;
		case 'ppicid':
		case 'spicid':
			//检索图片
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('pic')." WHERE picid='$id' LIMIT 1");
			$pic = $_SGLOBAL['db']->fetch_array($query);
			//图片不存在
			if(empty($pic)) {
				showmessage('view_images_do_not_exist');
			}

			//检索空间
			$tospace = getspace($pic['uid']);
			break;
		case 'profid':
			//检索图片
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('mtag')." WHERE tagid='$id' AND tagtype=1 LIMIT 1");
			$prof = $_SGLOBAL['db']->fetch_array($query);
			//图片不存在
			if(empty($prof)) {
				showmessage('view_prof_do_not_exist');
			}
            //检索空间 
            $tospace['prof_name'] = $prof['tagname'];
            $tospace['uid'] = $_SGLOBAL['supe_uid'];
            break;
		case 'blogid':
			//读取日志
			$query = $_SGLOBAL['db']->query("SELECT b.*, bf.target_ids
				FROM ".tname('blog')." b
				LEFT JOIN ".tname('blogfield')." bf ON bf.blogid=b.blogid
				WHERE b.blogid='$id'");
			$blog = $_SGLOBAL['db']->fetch_array($query);
			//日志不存在
			if(empty($blog)) {
				showmessage('view_to_info_did_not_exist');
			}

			//是否允许评论
			if(!empty($blog['noreply'])) {
				showmessage('do_not_accept_comments');
			}
			if($blog['target_ids']) {
				$blog['target_ids'] .= ",$blog[uid]";
			}
			//检索空间
			$tospace = getspace($blog['uid']);
			break;
		case 'sid':
			//读取日志
			$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('share')." WHERE sid='$id'");
			$share = $_SGLOBAL['db']->fetch_array($query);
			//日志不存在
			if(empty($share)) {
				showmessage('sharing_does_not_exist');
			}

			//检索空间
			$tospace = getspace($share['uid']);
			break;
		default:
			showmessage('non_normal_operation');
			break;
	}
	if(empty($tospace)) {
		showmessage('space_does_not_exist');
	}
	//黑名单
	if(isblacklist($tospace['uid'])) {
		showmessage('is_blacklist');
	}
}

//删除评论
function deletecomments($cids) {
	global $_SGLOBAL;

	$blognums = $spaces = $newcids = $dels = array();
	$allowmanage = checkperm('managecomment');

	$query = $_SGLOBAL['db']->query("SELECT * FROM ".tname('comment')." WHERE cid IN (".simplode($cids).")");
	while ($value = $_SGLOBAL['db']->fetch_array($query)) {
		if($allowmanage || $value['authorid'] == $_SGLOBAL['supe_uid'] || $value['uid'] == $_SGLOBAL['supe_uid']) {
			$newcids[] = $value['cid'];
			if($value['idtype'] == 'blogid') {
				$blognums[$value['id']]++;
			}
			if($value['authorid'] != $value['uid']) {
				$spaces[$value['authorid']]++;
			}
			$dels[] = $value;
		}
	}

	if(empty($dels)) return array();


	//数据删除
	$_SGLOBAL['db']->query("DELETE FROM ".tname('comment')." WHERE cid IN (".simplode($newcids).")");

	//统计数据
	$nums = renum($blognums);
	foreach ($nums[0] as $num) {
		$_SGLOBAL['db']->query("UPDATE ".tname('blog')." SET replynum=replynum-$num WHERE blogid IN (".simplode($nums[1][$num]).")");
	}

	//积分
	if($spaces) {
	//	updatespaces($spaces, 'comment');
	}
	
    updatespacestatus('pay', 'prof_cmt');
	return $dels;
}

?>
